package com.yc.thread.fairNofairLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * cy 20200708
 *
 * // 通过ReentrantLock 实现死锁案例
 */
public class ReentrantLockDeadLock {

    private static Lock firstLock = new ReentrantLock();
    private static Lock secondLock = new ReentrantLock();


    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadDemo(firstLock, secondLock));
        Thread thread2 = new Thread(new ThreadDemo(secondLock, firstLock));
        thread1.start();
        thread2.start();
        thread1.interrupt();
    }

    static class ThreadDemo extends Thread {
        Lock lock1;
        Lock lock2;

        public ThreadDemo(Lock lock1, Lock lock2){
            this.lock1 = lock1;
            this.lock2 = lock2;
        }

        @Override
        public void run() {
            try {
                lock1.lockInterruptibly();
                TimeUnit.SECONDS.sleep(1);
                lock2.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + "获取了资源，正常结束了");
            }
        }
    }
}
